/*
 *  This file was originally created by Ireneusz Grala in August 2010
 *  e-mail: ireneusz.grala@wp.pl
 *  
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace SimpleGPSApp.Base
{
    public class Common
    {
        public static object locker = new object();

        public static bool SaveTxtFile(string path, FileMode mode, string message, bool _writeLine)
        {
            lock (locker)
            {
                FileStream fs = new FileStream(path, mode, FileAccess.ReadWrite, FileShare.Read);
                if (fs == null)
                {
                    IRQBaseFunctions.ErrorLog.WriteError(
                        Config.ErrorLogFileName, 
                        "SaveTxtFile: Error in file operation. File path: "
                        + path + " File mode: " + mode.ToString());
                    return false;
                }

                StreamWriter sw = new StreamWriter(fs);
                if (sw == null)
                {
                    IRQBaseFunctions.ErrorLog.WriteError(Config.ErrorLogFileName, "SaveTxtFile: Failed to initialize stream");
                    return false;
                }
                try
                {
                    if (_writeLine)
                        sw.WriteLine(message);
                    else
                        sw.Write(message);

                    return true;
                }
                catch (Exception e)
                {
                    IRQBaseFunctions.ErrorLog.WriteError(Config.ErrorLogFileName, "SaveTxtFile: " + e.ToString());
                    return false;
                }
                finally
                {
                    sw.Flush();
                    sw.Close();
                    fs.Close();
                }
            }
        }
    }
}
